<template>
  <div class="app-container">
    <el-form :inline="true" :model="dataForm" @submit.native.prevent @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input placeholder="品名" v-model="dataForm.productName" :clearable="true" size="mini">
          <template slot="prepend">品名</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="规格" v-model="dataForm.productSpec" :clearable="true" size="mini">
          <template slot="prepend">规格</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="编码" v-model="dataForm.productGmp" :clearable="true" size="mini">
          <template slot="prepend">编码</template>
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-input placeholder="批号" v-model="dataForm.batchNum" :clearable="true" size="mini">
          <template slot="prepend">批号</template>
        </el-input>
      </el-form-item>

      <el-form-item v-if="userInfo.types.length != 0">
        <el-select v-model="dataForm.checkTypeId" clearable placeholder="全部分类" size="mini">
          <el-option
            v-for="t in userInfo.types"
            :key="t.checkTypeId"
            :label="t.checkTypeName"
            :value="t.checkTypeId">
          </el-option>
      	</el-select>
      </el-form-item>

      <el-form-item>
        <el-select v-model="dataForm.status" @change="searchData()" clearable placeholder="全部状态" size="mini">
          <el-option label="未开始" value="1" />
          <el-option label="已开始" value="1.5" />
          <el-option label="已完成" value="2" />
      	</el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" class="pan-btn primary-btn" @click="searchData()" icon="el-icon-search" size="mini">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-table
    	:data="dataList"
      v-loading="dataListLoading"
    	border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column
        prop="checkId"
        header-align="center"
        align="center"
        label="编号"
        width="80">
      </el-table-column>
      <el-table-column
      	prop="itemStatus"
      	header-align="center"
      	align="center"
      	label="状态"
        width="80">
        <template slot-scope="{row}">
          <el-tag :type="row.itemStatus == 2 ? 'success' : row.startTime == null ? 'danger' : 'warning'" size="small">
            {{ row.itemStatus == 2 ? '已完成' : row.startTime == null ? '未开始' : '已开始' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="checkTypeName"
        header-align="center"
        align="center"
        label="分类"
        width="100">
        <template slot-scope="{row}">
          {{ row.checkTypeName }}
        </template>
      </el-table-column>
      <el-table-column
        prop="productName"
        header-align="center"
        align="center"
        label="品名">
      </el-table-column>
      <el-table-column
        prop="productSpec"
        header-align="center"
        align="center"
        label="规格">
        <template slot-scope="{row}">
          <span v-html="row.productSpec"></span>
        </template>
      </el-table-column>
      <el-table-column
        prop="productGmp"
        header-align="center"
        align="center"
        label="编码">
      </el-table-column>
      <el-table-column
        prop="batchNum"
        header-align="center"
        align="center"
        label="批号">
      </el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="考察信息"
        width="100">
        <template slot-scope="{row}">
          <span>{{ wk(row.checkTypeId) ? (row.stabilityModeName + row.timeValue + row.timeName) : "" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="inspectionItemName"
        header-align="center"
        align="center"
        label="检验项目">
      </el-table-column>
      <el-table-column
        v-if="dataForm.status != '1'"
        prop="startTime"
        header-align="center"
        align="center"
        label="检验开始时间">
        <template slot-scope="{row}">
          {{ row.startTime | changeTime }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="dataForm.status == '' || dataForm.status == '1.5'"
        prop="startTime"
        header-align="center"
        align="center"
        label="预计结束时间">
        <template slot-scope="{row}">
          {{ row.endTime | changeTime }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="dataForm.status == '' || dataForm.status == '2'"
        prop="endTime"
        header-align="center"
        align="center"
        label="检验结束时间">
        <template slot-scope="{row}">
          {{ row.endTime | changeTime }}
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="操作"
        width="100">
        <template slot-scope="scope">
          <template v-if="userInfo.username == 'admin' ? true : userInfo.inspectionGroupIds == null ? false : userInfo.inspectionGroupIds.indexOf(scope.row.inspectionGroupId) > -1">
            <el-button type="success" class="pan-btn success-btn" size="mini" v-if="(scope.row.status == 4 || scope.row.status == 5 || scope.row.status == 6) && scope.row.startTime == null" @click="showStartTimeSelect(scope.row)">开始</el-button>
            <el-button type="warning" class="pan-btn warning-btn" size="mini" v-if="(scope.row.status == 4 || scope.row.status == 5 || scope.row.status == 6) && scope.row.startTime != null" @click="showStartTimeSelect(scope.row)">修改</el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="判定"
        width="200">
        <template slot-scope="{row}">
          <template v-if="showVerdict(row)">
            <el-radio-group @change="changeItemVerdict(row)" v-model="row.itemVerdict" :disabled="row.verdictDisabled" size="mini">
              <el-radio-button :label="0">符合规定</el-radio-button>
              <el-radio-button :label="1">不符合规定</el-radio-button>
            </el-radio-group>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="详情"
        width="100">
        <template slot-scope="scope">
          <el-button type="info" class="pan-btn info-btn" size="mini" @click="info(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog
      title="开始时间"
      :visible.sync="selectTimeVisible"
      :before-close="closeSelectTime"
      :append-to-body="true"
      :close-on-click-modal="false"
      width="50%">
      <el-row>
        <el-tooltip effect="dark" :content="startIsFullLast ? '不填充' : '自动填充'" placement="top">
          <el-switch
            style="float: right;"
            v-model="startIsFullLast"
            @change="changeStartFullLast"
            active-color="#7cbd36"
            inactive-color="#ff4949"
            inactive-text="上一单">
          </el-switch>
        </el-tooltip>
      </el-row>
      <el-row style="margin-top: 5px">
        <el-card>
          <el-form>
            <el-form-item label="检验开始时间:">
              <el-date-picker
                v-model="waitRow.startTime"
                @change="changeStartTime"
                :clearable="false"
                align="right"
                type="date"
                style="width: 100%;"
                placeholder="开始"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预计结束时间:">
              <el-date-picker
                v-model="waitRow.endTime"
                :clearable="false"
                align="right"
                type="date"
                style="width: 100%"
                placeholder="结束"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="检验人:">
              <el-select
                v-model="waitRow.inspectionUser"
                value-key="userId"
                @change="setInspectionUser"
                filterable
                placeholder="必填"
                style="width: 100%" >
                <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.name + '(' + item.username + ')'"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预计检验结果:">
              <el-input @change="setItemConclusion" v-if="waitRow.isNumber == 0" v-model="waitRow.conc.itemConclusionValue" placeholder="必填(数字)">
                <template slot="append">
                  <span v-html="waitRow.conc.itemConclusionUnit"></span>
                </template>
              </el-input>
              <el-input @change="setItemConclusion" v-else v-model="waitRow.conc.itemConclusion" placeholder="必填" />
            </el-form-item>
          </el-form>
        </el-card>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSelectTime">取 消</el-button>
        <el-button type="primary" :loading="starting" @click="start">确 定</el-button>
    	</span>
    </el-dialog>

    <check-info
      v-if="infoVisible"
      @close="close('infoVisible')"
      @refreshData="getDataList"
      :childDataForm="childDataForm" />

  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import CommonMethod from '@/views/mixin/common'
  import { CODE_OK } from '@/common/js/config'
  import { isBlank,dateCompare,parseTime } from '@/common/js/utils'
  import { isNumber } from '@/common/js/validate'
  import { getItemTimeBook,startInspectionItem,getUserList,verdictItem,getInspectionGroupLastOptItem } from '@/api/check'
  import CheckInfo from '@/views/modules/process/common/check-info'
  export default{
    name: 'jianyanshijian',
    mixins: [CommonMethod],
    components: {
    	CheckInfo
    },
    data() {
      return{
        currentStatus: 4,
        dataForm: {
          status: '1.5'
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        childDataForm: '',
        infoVisible: false,
        selectTimeVisible: false,
        starting: false,
        startIsFullLast: false,
        waitRow: {
          conc: {}
        },
        userList: []
      }
    },
    computed: {
      ...mapGetters([
         'userInfo'
      ])
    },
    mounted() {
      this.getInfo()
    },
    methods: {
      changeStartFullLast() {
        if (this.startIsFullLast) {
          const params = {
            groupId: this.waitRow.inspectionGroupId,
            isWswGroup: 0
          }
          //改变开始时填充状态
          getInspectionGroupLastOptItem(params).then(res => {
            if (res.code === CODE_OK) {
              let item = res.item
              this.waitRow.startTime = item.startTime
              this.changeStartTime()
              this.waitRow.inspectionUser = {
                userId: item.inspectionUserId,
                name: item.inspectionUserName
              }
              this.setInspectionUser()
              this.waitRow.conc = item.conclusions[0]
              this.setItemConclusion()
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      //请验单状态（检验中，等待中，待结论），几个项目必填项不为空
      showVerdict(row) {
        if (typeof row == 'object') {
          return (row.status == 4 || row.status == 5 || row.status == 6) &&
          row.startTime != null && row.endTime != null && row.inspectionUserId != null && row.itemConclusionMerge != null && row.itemConclusionMerge != ''
        }
        return false
      },
      changeItemVerdict(row) {
        const data = {
          checkId: row.checkId,
          checkItemId: row.checkItemId,
          itemStatus: row.itemStatus,
          itemVerdict: row.itemVerdict,
          groupId: row.inspectionGroupId
        }
        verdictItem(data).then(res => {
          if (res.code === CODE_OK) {
            this.$message.success('提交成功')
            this.getDataList()
          }else{
            this.$message.error(res.msg)
          }
        })
      },
      setItemConclusion() {
        if (this.waitRow.isNumber == 0) {
          if (!isNumber(this.waitRow.conc.itemConclusionValue)) {
            this.$message.error('请输入数字类型')
            this.waitRow.conc.itemConclusionValue = null
            return
          }else{
            this.waitRow.conc.itemConclusion = this.waitRow.conc.itemConclusionValue + (isBlank(this.waitRow.conc.itemConclusionUnit) ? '' : this.waitRow.conc.itemConclusionUnit)
          }
        }
        this.waitRow.itemConclusionMerge = this.waitRow.conc.itemConclusion
        this.waitRow.itemConclusionCount = 1
      },
      setInspectionUser() {
        this.waitRow.inspectionUserId = this.waitRow.inspectionUser.userId
        this.waitRow.inspectionUserName = this.waitRow.inspectionUser.name
      },
      changeStartTime() {
        if (!isBlank(this.waitRow.startTime)) {
          let addDay = 1
          if (this.waitRow.inspectionItemName.indexOf('微生物限度') > -1) {
            addDay = 5
          }else if(this.waitRow.inspectionItemName.indexOf('无菌') > -1) {
            addDay = 14
          }
          this.waitRow.endTime = this.moment(this.waitRow.startTime).add(addDay, 'd').format('YYYY-MM-DD HH:mm:ss')
        }
      },
      formVerify() {
        console.log(this.waitRow)
        if (isBlank(this.waitRow.startTime)) {
          this.$message.error('检验开始时间不能为空')
          return false
        }
        if (!dateCompare(this.waitRow.dispenseDate,this.waitRow.startTime)) {
          this.$message.error("检验开始时间必须晚于分样时间")
          return false
        }
        if (isBlank(this.waitRow.endTime)) {
          this.$message.error('预计结束时间不能为空')
          return false
        }
        if (isBlank(this.waitRow.inspectionUserId)) {
          this.$message.error('检验人不能为空')
          return false
        }
        if (isBlank(this.waitRow.itemConclusionMerge)) {
          this.$message.error('预计检验结果不能为空')
          return false
        }
        return true
      },
      start() {
        if (this.formVerify()) {
          startInspectionItem(this.waitRow).then(res => {
            if (res.code === CODE_OK) {
              this.$message.success('提交成功，记得及时做判定')
              this.closeSelectTime()
              this.searchData()
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      info(row) {
        this.childDataForm = {
          currentStatus: this.currentStatus,
          info: row
        }
        this.infoVisible = !this.infoVisible
      },
      searchData() {
      	this.pageIndex=1
      	this.getDataList()
      },
      getInfo() {
        this.getDataList()
      },
      getDataList() {
        this.dataListLoading = true
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          inspectionGroupIds: this.userInfo.inspectionGroupIds,
          status: this.dataForm.status || null,
          checkTypeId: this.dataForm.checkTypeId || null,
          productName: this.dataForm.productName || null,
          productSpec: this.dataForm.productSpec || null,
          productGmp: this.dataForm.productGmp || null,
          batchNum: this.dataForm.batchNum || null
        }
        getItemTimeBook(params).then(res => {
        	if (res.code === CODE_OK) {
        		this.dataList = res.page.list.map(r => {
              let now = parseTime(new Date())
              this.$set(r,'verdictDisabled', true)
              if (!isBlank(r.endTime)) {
                r.verdictDisabled = !dateCompare(r.endTime, now) || r.status > 6
              }
              return r
            })
        		this.totalPage = res.page.totalCount
        	}else{
        		this.$message.error(res.msg)
        	}
        	this.dataListLoading = false
        })
      },
      showStartTimeSelect(row) {
        this.selectTimeVisible = true
        this.waitRow = JSON.parse(JSON.stringify(row))
        if (this.waitRow.inspectionUserId != null) {
          this.$set(this.waitRow,'inspectionUser',{
            userId: this.waitRow.inspectionUserId,
            name: this.waitRow.inspectionUserName
          })
        }
        if (this.waitRow.conc == null) {
          this.$set(this.waitRow,'conc',{
            itemConclusionUnit: this.waitRow.insideInspectionItemValueUnit
          })
        }
        if (this.userList.length == 0) {
          const params = {
            groupId: row.inspectionGroupId
          }
          getUserList(params).then(res => {
            if (res.code === CODE_OK) {
              this.userList = res.list
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      close(val) {
        this.childDataForm = ''
        this[val] = !this[val]
      },
      closeSelectTime() {
        this.waitRow = {
          conc: {}
        }
        this.startIsFullLast = false
        this.selectTimeVisible = false
      }
    }
  }
</script>

<style scoped>
  >>> .el-form-item__content {
    line-height: normal;
  }
</style>
